#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <ctime>
#include "Task.hpp"
#include "RingQueue.hpp"

using namespace std;

struct ThreadData
{
    RingQueue<Task>* rq;
    std::string threadname;
};

void* Productor(void* args)
{
    //sleep(3);
    ThreadData *td = static_cast<ThreadData*>(args);
    //RingQueue<int>* rq = static_cast<RingQueue<int>*>(args);
    RingQueue<Task>* rq = td->rq;
    std::string name = td->threadname;

    int len = opera.size();

    while (true)
    {
        //1. 获取数据
        int data1 = rand() % 10 + 1;

        int data2 = rand() % 10 +1;

        char op = opera[rand() % len];


        //2. 生产数据
        //rq->Push(data);
        Task t(data1,data2,op);
        rq->Push(t);
        cout << "Productor a data done, data is : " << t.GetResult() << " ,who : " << name << endl;
        //sleep(1);
    }

    return nullptr;
}

void* Consumer(void* args)
{   
    //sleep(3);

    ThreadData *td = static_cast<ThreadData*>(args);
    //RingQueue<int>* rq = static_cast<RingQueue<int>*>(args);
    RingQueue<Task>* rq = td->rq;
    std::string name = td->threadname;

    while (true)
    {
        //1. 消费数据
        //int data = 0;
        Task t;
        rq->Pop(&t);

       

        //2. 处理数据
        t();

        std::cout << "Consumer get data, data is : " << t.GetTask() << " ,result : " << t.GetResult() << std::endl;
        sleep(1);
    }

    return nullptr;
}

int main()
{
    srand(time(nullptr) ^ getpid());

    RingQueue<Task> *rq = new RingQueue<Task>();

    pthread_t c[5],p[3];

    for (int i = 0; i < 5; i++)
    {
        ThreadData *td = new ThreadData;
        td->rq = rq;
        td->threadname = "Consumer-" + std::to_string(i);
        pthread_create(c + i,nullptr,Consumer,td);
    }
    
    for (int i = 0; i < 3; i++)
    {
        ThreadData *td = new ThreadData;
        td->rq = rq;
        td->threadname = "Productor-" + std::to_string(i);
        pthread_create(p + i,nullptr,Productor,td);

    }
    
    for (int i = 0; i < 5; i++)
    {
        pthread_join(c[i],nullptr);
    }
  
    for (int i = 0; i < 3; i++)
    {
        pthread_join(p[i],nullptr);

    }
   
    delete rq;
    return 0;
}